﻿using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;

namespace Middleware
{
    public static class Helper
    {
        public static void SerializeObject(string filename, object objectToSerialize) {
            using (Stream stream = File.Open(filename, FileMode.Create)) {
                BinaryFormatter bFormatter = new BinaryFormatter();
                bFormatter.Serialize(stream, objectToSerialize);
            }
        }

        public static T DeserializeObject<T>(string filename) {
            using (Stream stream = File.Open(filename, FileMode.OpenOrCreate)) {
                BinaryFormatter bFormatter = new BinaryFormatter();
                return (T)bFormatter.Deserialize(stream);
            }
        }

        public static int GetAvailablePort() {
            TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 0);
            listener.Start();
            int portNumber = ((IPEndPoint)listener.LocalEndpoint).Port;
            listener.Stop();
            return portNumber;
        }
    }
}
